package com.saifan.wyy_ov.ui.onlishop;

import java.util.ArrayList;
import java.util.List;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.CommonDataBean;
import com.saifan.wyy_ov.data.bean.GroupBuyBean;
import com.saifan.wyy_ov.data.bean.PopCategoryBean;
import com.saifan.wyy_ov.data.bean.PopCategoryBean.Type;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.RefreshLayout;
import com.saifan.wyy_ov.ui.view.RefreshLayout.OnLoadListener;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.DensityUtil;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

import lomasky.ma.xui.BaseRecyclerViewAdapter;
import lomasky.ma.xui.BaseViewHolder;
import lomasky.ma.xui.ItemDivider;
import lomasky.ma.xui.RecyclerViewAdapter;
import lomasky.ma.xui.WrapContentLineaLayoutManager;

public class GroupBuyActivity extends BaseActivity {

    private Toolbar toolbar;
    private ListView listView;
    private TextView tv_title, tv_category;
    private RefreshLayout refreshLayout;
    private AdapterGroupBuy adapterGroupBuy;
    private CommonDataBean requestBean;
    private GetData getData;
    private int page = 0;// 第几页
    protected List<GroupBuyBean> groupBuyBeans = new ArrayList<GroupBuyBean>();
    private PopCategoryBean popCategoryBean;
    private PopupWindow popupWindow;
    private List<PopCategoryBean> popList = new ArrayList<PopCategoryBean>();
    RecyclerViewAdapter<PopCategoryBean.Type> adapterRight;
    RecyclerViewAdapter<PopCategoryBean> adapterLeft;
    private int leftPosition = 0, rightPosition = -1;
    protected List<PopCategoryBean> dataList;
    protected String storeType;
    private RelativeLayout loadlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int mType = getIntent().getIntExtra("Type", 1);
        setContentView();
        if (mType == 1) {
            tv_title.setText("周边团购");
        } else if (mType == 2) {
            tv_title.setText("店铺促销");
        }
        requestBean = new CommonDataBean();
        requestBean.setYXDID(getRoomInfoBean().getXMBS());
        requestBean.setType(mType);
        getData = new GetData();
        popList = new ArrayList<PopCategoryBean>();
        popCategoryBean = new PopCategoryBean();
        popCategoryBean.setSelectState(false);
        popCategoryBean.setTypeName("全部");
        popCategoryBean.setChildStoreType(new ArrayList<PopCategoryBean.Type>());
        popList.add(popCategoryBean);
        query();
        getStoreType();
    }

    private void setContentView() {
        setContentView(R.layout.activity_group_buy);
        loadlay = (RelativeLayout) findViewById(R.id.loading_lay);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        tv_category = (TextView) findViewById(R.id.tv_category);
        tv_title = (TextView) findViewById(R.id.title);
        listView = (ListView) findViewById(R.id.listView);
        refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                // TODO Auto-generated method stub
                page = 0;
                refreshLayout.setRefreshing(true);
                query();
            }
        });
        refreshLayout.setOnLoadListener(new OnLoadListener() {
            @Override
            public void onLoad() {
                // TODO Auto-generated method stub

                page++;
                refreshLayout.setLoading(true);
                query();

            }
        });
        adapterGroupBuy = new AdapterGroupBuy(GroupBuyActivity.this, groupBuyBeans);
        listView.setAdapter(adapterGroupBuy);
    }

    public void query() {
        if (groupBuyBeans.isEmpty()) {
            loadlay.setVisibility(View.VISIBLE);
        }
        requestBean.setPage(page);
        refreshLayout.setRefreshing(true);
        getData.getDataJson(this, Api.GroupBuy.SURROUNDGROUPBUY, requestBean, "", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                // TODO Auto-generated method stub
                loadlay.setVisibility(View.GONE);
                refreshLayout.setRefreshing(false);
                List<GroupBuyBean> list = new Gson().fromJson(json, new TypeToken<List<GroupBuyBean>>() {
                }.getType());
                if (list != null && list.size() > 0) {
                    if (page == 0) {
                        groupBuyBeans = list;
                    } else {
                        groupBuyBeans.addAll(list);
                    }
                    adapterGroupBuy.setGroupBuyBeans(groupBuyBeans);
                    adapterGroupBuy.notifyDataSetChanged();
                } else {
                    if (page == 0) {
                        ToastUtil.showToast(GroupBuyActivity.this, "暂无更多团购信息");

                    }
                    if (page > 0) {
                        page--;
                    }

                }


                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);
                loadlay.setVisibility(View.GONE);

            }

            @Override
            public void onFailed(String str) {
                // TODO Auto-generated method stub

                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);
                loadlay.setVisibility(View.GONE);


            }
        });
    }


    // 选择店铺类别
    @SuppressWarnings("deprecation")
    private void showSelectPop() {
        String text = tv_category.getText().toString();
        if (dataList != null && dataList.size() > 0) {
            for (int i = 0; i < popList.size(); i++) {
                for (int j = 0; j < popList.get(i).getChildStoreType().size(); j++) {
                    Type type = popList.get(i).getChildStoreType().get(j);
                    if (text.equals(type.getTypeName())) {
                        leftPosition = i;
                        type.setSelectState(true);
                        popList.get(i).setSelectState(true);
                    } else {
                        type.setSelectState(false);
                    }
                }
            }
            if (text.equals("全部")) {
                popList.get(0).setSelectState(true);
                popList.get(0).setTypeName("全部");
            }
            View contentView = getLayoutInflater().inflate(R.layout.category_pop, null);
            RecyclerView leftListView = (RecyclerView) contentView.findViewById(R.id.left_listview);
            RecyclerView rightListView = (RecyclerView) contentView.findViewById(R.id.right_listview);
            leftListView.setLayoutManager(new LinearLayoutManager(this));
            rightListView.setLayoutManager(new LinearLayoutManager(this));

            popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, false);
            adapterLeft = new RecyclerViewAdapter<PopCategoryBean>(GroupBuyActivity.this,  R.layout.list_category) {
                @Override
                public void onBind(BaseViewHolder holder, PopCategoryBean item, int p) {
                   CheckBox checkBox= holder.getCheckBox(R.id.checkbox);
                    checkBox.setChecked(item.isSelectState());
                    checkBox.setText(item.getTypeName());


                }
            };
            adapterLeft.setData(popList);
            leftListView.setAdapter(adapterLeft);
            adapterLeft.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int i) {
                    if (rightPosition != -1 && leftPosition != 0) {
                        popList.get(leftPosition).getChildStoreType().get(rightPosition).setSelectState(false);
                    }
                    for (int j = 0; j < popList.size(); j++) {
                        if (j == i) {
                            popList.get(j).setSelectState(true);
                            leftPosition = i;
                        } else {
                            popList.get(j).setSelectState(false);
                        }
                    }
                    adapterLeft.setData(popList);
                    adapterLeft.notifyDataSetChanged();
                    List<PopCategoryBean.Type> subList = popList.get(leftPosition).getChildStoreType();
                    adapterRight.setData(subList);

                    adapterRight.notifyDataSetChanged();
                    if (i == 0) {
                        tv_category.setText("全部");
                        popupWindow.dismiss();
                        page = 0;
                        storeType = "全部";
                        requestBean.setStoreType(null);
                        groupBuyBeans.clear();
                        query();
                        return;
                    }
                }
            });
            adapterRight = new RecyclerViewAdapter<PopCategoryBean.Type>(GroupBuyActivity.this, R.layout.list_type) {
                @Override
                public void onBind(BaseViewHolder baseViewHolder, PopCategoryBean.Type type, int i) {
                    baseViewHolder.setText(  R.id.checkbox, type.getTypeName());
                }


            };
            adapterRight.setData(popList.get(leftPosition).getChildStoreType());

            rightListView.setAdapter(adapterRight);
            adapterRight.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
                @Override
              public void onItemClick(View view, int i) {
                    rightPosition = i;
                    adapterRight.setData(popList.get(leftPosition).getChildStoreType());
                    adapterRight.notifyDataSetChanged();
                    tv_category.setText(popList.get(leftPosition).getChildStoreType().get(i).getTypeName());
                    popupWindow.dismiss();
                    storeType = tv_category.getText().toString();
                    page = 0;
                    adapterGroupBuy.getGroupBuyBeans().clear();
                    adapterGroupBuy.notifyDataSetChanged();
                    requestBean.setStoreType(storeType);
                    query();
                }
            });
            // 需要设置一下此参数，点击外边可消失
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            // 设置点击窗口外边窗口消失
            popupWindow.setOutsideTouchable(true);
            // 设置此参数获得焦点，否则无法点击
            popupWindow.setFocusable(true);
            popupWindow.showAsDropDown(toolbar);
        } else {
            getStoreType();
            showSelectPop();
        }
    }

    // 获取店铺类别
    private void getStoreType() {
        getData.httpGetDataJson(GroupBuyActivity.this, Api.StoreList.GETSTORETYPE, "", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                dataList = (new Gson()).fromJson(json, new TypeToken<List<PopCategoryBean>>() {
                }.getType());
                popList.addAll(dataList);
            }

            @Override
            public void onFailed(String str) {
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.order_menu, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_more) {
            if (dataList != null && dataList.size() > 0) {
                showSelectPop();
            }

        } else {
        }
        return super.onOptionsItemSelected(item);

    }
}
